//
//  NumStepField.swift
//  xzseller
//
//  Created by zhuxietong on 2021/1/22.
//

import Foundation
import Eelay

open class NumStepField:FieldView{
    public var limit = NumLimit()
    {
        didSet{
            let newValue = mo.model[int:FK.value,0]
            reduceBt.isEnabled = true
            addBt.isEnabled = true
            if newValue > (limit.max)
            {
                addBt.isEnabled = false
            }
            
            if newValue < (limit.min)
            {
                reduceBt.isEnabled = false
                //            self.minAlert.alert()
            }
        }
    }
    public var value:Int = 1
    {
        didSet{
            numT.text = "\(value)"
        }
    }
    
    public var numT = UITextField()
    public let addBt = UIButton()
    public let reduceBt = UIButton()
    
    public var changeNumValue:(Int) ->Void = {_ in}
    open override func addLayoutRules() {
        let numB = UIView()
        self.eelay = [
            [numB,[ee.X],[ee.T.B],30],
            [numT,[ee.X.Y],30],
            [reduceBt,[numT,ee.L,ee.R,-1],[ee.T.L.B],30],
            [addBt,[numT,ee.R,ee.L,1],[ee.T.L.B],30],
        ]
        numT.text = "1"
        
        let color = UIColor.clear
        numB.backgroundColor = color
        numT.textAlignment = .center
        numT.backgroundColor = color
        reduceBt.backgroundColor = color
        addBt.backgroundColor = color
        addBt.ui.font(size: 14).ncolor(color: ._foreground).ntitle(title: "+")
        reduceBt.ui.font(size: 14).ncolor(color: ._foreground).ntitle(title: "-")
        //            self.backgroundColor = UIColor(shex:"#aaa")
        self.bsui.background(color: ._tableBackground).set(radius: 2, width: TP.separatorHeight, color: ._separator)
        
        _ = numT.ui.font12.text(color: ._tint).center
        numT.tintColor = UIColor._tint
        numT.keyboardType = .numberPad
        addBt.tag = 1
        reduceBt.tag = -1
        
        addBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
        reduceBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
    }
    
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        self.bsui.background(color: ._tableBackground).set(radius: 2, width: TP.separatorHeight, color: ._separator)

    }
    
    open override func mo_model_reload() {
        limit.min = mo.model[int:FK.min_num,0]
        limit.max = mo.model[int:FK.max_mum,999]
        limit.minMask = mo.model[FK.min_num_mark,""]
        limit.maxMask = mo.model[FK.max_mum_mark,""]
        self.value = mo.model[int:FK.value,0]
    }
    
    
    @objc open func updateNum(sender:UIButton) {
//        print("+++____S_S_S|\(sender)")
        let num = sender.tag
        let newValue = self.value + num
        reduceBt.isEnabled = true
        addBt.isEnabled = true
        if newValue > (limit.max)
        {
            if limit.maxMask.len > 0
            {
                self.limit.maxMask.alert()
            }
//            addBt.isEnabled = false
        }
        if newValue < (limit.min)
        {
//            reduceBt.isEnabled = false
            //            self.minAlert.alert()
        }
        if (newValue >= limit.min) && (newValue<=limit.max){
            self.value = newValue
            self.save("\(newValue)")
            self.changeNumValue(newValue)
        }
        //        self.willSetNewValue(newValue: newValue)
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let t = textField.text ?? ""
        if t.len < 1{
            textField.text = "0"
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard var text = textField.text else {
            return true
        }
        if string == "-"{
            return false
        }

        if string.len < 1{
            return true
        }
        
        if range.location <= text.count{
            let index = text.index(text.startIndex, offsetBy: range.location)
            text.insert(contentsOf: string, at: index)
        }
       
        if let _ = Regex("^[1-9]\\d*$").firstMatch(in: text){
            if let newValue = Int(text){
                
                if (newValue >= limit.min) && (newValue<=limit.max){
                    self.value = newValue
                    self.changeNumValue(newValue)
                    return true
                }

               
            }
//            updatePrice()
            return false
        }
//        if let _ = Regex("\\d+\\.\\d{1,10}$").firstMatch(in: text){
//            updatePrice()
//            return true
//        }
        return false
       
    }
    override open var intrinsicContentSize: CGSize{
        return [90,30]
    }
    
}
open class PriceStepField:FieldView{
    public var limit = NumLimit()
    {
        didSet{
            let newValue = mo.model[int:FK.value,0]
            reduceBt.isEnabled = true
            addBt.isEnabled = true
            if newValue > (limit.max)
            {
                addBt.isEnabled = false
            }
            
            if newValue < (limit.min)
            {
                reduceBt.isEnabled = false
                //            self.minAlert.alert()
            }
        }
    }
    public var value:CGFloat = 1
    {
        didSet{
            numT.text = "\(value.validDigital)"
        }
    }
    
    public var numT = UITextField()
    public let addBt = UIButton()
    public let reduceBt = UIButton()
    
    public var changeNumValue:(CGFloat) ->Void = {_ in}
    open override func addLayoutRules() {
        let numB = UIView()
        self.eelay = [
            [numB,[ee.X],[ee.T.B],30],
            [numT,[ee.X.Y],30],
            [reduceBt,[numT,ee.L,ee.R,-1],[ee.T.L.B],30],
            [addBt,[numT,ee.R,ee.L,1],[ee.T.L.B],30],
        ]
        numT.text = "1"
        
        let color = UIColor.clear
        numB.backgroundColor = color
        numT.textAlignment = .center
        numT.backgroundColor = color
        reduceBt.backgroundColor = color
        addBt.backgroundColor = color
        addBt.ui.font(size: 14).ncolor(color: ._foreground).ntitle(title: "+")
        reduceBt.ui.font(size: 14).ncolor(color: ._foreground).ntitle(title: "-")
        //            self.backgroundColor = UIColor(shex:"#aaa")
        self.bsui.background(color: ._tableBackground).set(radius: 2, width: TP.separatorHeight, color: ._separator)
        
        _ = numT.ui.font12.text(color: ._tint).center
        numT.tintColor = UIColor._tint
        numT.keyboardType = .numberPad
        addBt.tag = 1
        reduceBt.tag = -1
        
        addBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
        reduceBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
    }
    
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        self.bsui.background(color: ._tableBackground).set(radius: 2, width: TP.separatorHeight, color: ._separator)

    }
    
    open override func mo_model_reload() {
        limit.min = mo.model[int:FK.min_num,0]
        limit.max = mo.model[int:FK.max_mum,999]
        limit.minMask = mo.model[FK.min_num_mark,""]
        limit.maxMask = mo.model[FK.max_mum_mark,""]
        self.value = mo.model[float:FK.value,0]
    }
    
    
    @objc open func updateNum(sender:UIButton) {
//        print("+++____S_S_S|\(sender)")
        let num = sender.tag
        let newValue = self.value + num.cg_floatValue
        reduceBt.isEnabled = true
        addBt.isEnabled = true
        if newValue > (limit.max.cg_floatValue)
        {
            if limit.maxMask.len > 0
            {
                self.limit.maxMask.alert()
            }
//            addBt.isEnabled = false
        }
        if newValue < (limit.min.cg_floatValue)
        {
//            reduceBt.isEnabled = false
            //            self.minAlert.alert()
        }
        if (newValue >= limit.min.cg_floatValue) && (newValue<=limit.max.cg_floatValue){
            self.value = newValue
            self.save("\(newValue)")
            self.changeNumValue(newValue)
        }
        //        self.willSetNewValue(newValue: newValue)
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let t = textField.text ?? ""
        if t.len < 1{
            textField.text = "0"
        }
    }
    
    @objc(textField:shouldChangeCharactersInRange:replacementString:) public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard var text = textField.text else {
            return true
        }
        if string == "-"{
            return false
        }

        if string.len < 1{
            return true
        }
        
        if range.location <= text.count{
            let index = text.index(text.startIndex, offsetBy: range.location)
            text.insert(contentsOf: string, at: index)
        }
       
        if text.mach(freg.price_can_zore.rawValue){
            let newValue = text.cg_floatValue
                
                if (newValue >= limit.min.cg_floatValue) && (newValue<=limit.max.cg_floatValue){
                    self.value = newValue
                    self.changeNumValue(newValue)
                    return true
                }

               
            
//            updatePrice()
            return false
        }
//        if let _ = Regex("\\d+\\.\\d{1,10}$").firstMatch(in: text){
//            updatePrice()
//            return true
//        }
        return false
       
    }
    override open var intrinsicContentSize: CGSize{
        return [90,30]
    }
    
}
